package com.example.demo.config.login;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * fileName:MyRealm
 * description:
 * author: LJV
 * createTime:2022/4/8 14:03
 * version:1.0.0
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取身份信息，就是用户实体
        Object primaryPrincipal = principalCollection.getPrimaryPrincipal();

        //模拟通过身份信息获取所有权限
        List<String> permissions = new ArrayList<>();
        permissions.add("user:list");
        permissions.add("user:create");
        permissions.add("user:delete");

        //将权限信息封装到AuthorizationInfo中，并返回
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //从被shiro封装成的token中取出我们传入的username
        String username = (String) authenticationToken.getPrincipal();
        //这里有一步去缓存或数据库查询的步骤,根据账号查询用户信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda().eq(User::getAccount,username);
        User user = userService.getOne(userQueryWrapper);
        //我直接定义了一个username，如果用户名不匹配，则报错用户名不存在。
        if(ObjectUtils.isEmpty(user) || !user.getAccount().equals(username)){
            throw new UnknownAccountException("账号不存在");
        }
        //返回一个新封装的认证实体，传入的是用户实体，数据库查出来的密码，和当前Realm的名字
        return new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
    }
}
